<!-- 能耗监控 -->
<template>
  <div class="monitor-container energy-monitor-container">
    <template v-if="!resolveVisible">
      <div class="tab-bar">
        <CustomTabs :tabList="tabList" :activeName="activeName" @tabSelect="handelTabSelected" />
      </div>
      <div class="flex-center table-top">
        <px-form ref="formRef" :model="queryParams" :inline="true" class="custom-form-ui search-form">
          <px-form-item label="监控周期" prop="cycle">
            <px-select v-model="queryParams.cycle" placeholder="请选择监控周期" clearable>
              <px-option v-for="item in cycleList" :key="item.value" :label="item.name" :value="item.value" />
            </px-select>
          </px-form-item>
          <px-form-item label="日期" prop="date">
            <px-date-picker
              v-model="queryParams.date"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
            />
          </px-form-item>
          <div class="search-form-btn">
            <px-button type="primary" @click="handleQuery">查询</px-button>
            <px-button @click="resetQuery">重置</px-button>
          </div>
        </px-form>
      </div>
      <div v-loading="tableLoading" class="table-content">
        <px-table height="calc(100vh - 370px)" :data="tableData" size="small" border class="common-table">
          <px-table-column type="index" label="序号" fixed width="55" align="center" />
          <px-table-column prop="monitorTypeName" label="监控类型" min-width="120" show-overflow-tooltip />
          <px-table-column prop="spcConfigName" label="报警项" min-width="120" show-overflow-tooltip />
          <px-table-column prop="period" label="监控周期" min-width="120" show-overflow-tooltip>
            <template #default="scope">
              {{ formatPeriod(scope.row.period) }}
            </template>
          </px-table-column>
          <px-table-column prop="alarmTime" label="报警时间" min-width="120" show-overflow-tooltip />
          <px-table-column prop="alarmLevel" label="报警等级" min-width="120" show-overflow-tooltip align="center">
            <template #default="scope">
              <span v-if="scope.row.alarmLevel === null">""</span>
              <px-tag v-else :type="scope.row.alarmLevel === 'S' ? 'warning' : 'danger'">{{ formatAlarm(scope.row.alarmLevel) }}</px-tag>
            </template>
          </px-table-column>
          <px-table-column prop="alarmValue" label="报警值" min-width="120" show-overflow-tooltip />
          <px-table-column prop="spcThresholdText" label="厂务内控值" min-width="120" show-overflow-tooltip />
          <px-table-column prop="hseThresholdText" label="HSE管控值" min-width="120" show-overflow-tooltip />
          <px-table-column prop="eventType" label="状态" min-width="120" show-overflow-tooltip>
            <template #default="scope">
              <div class="flex-center" :style="{ color: eventTypeStyle(scope.row.eventType) }">
                <span class="point mg-r-8" :style="{ background: eventTypeStyle(scope.row.eventType) }" />
                <span>{{ formatEventType(scope.row.eventType) }}</span>
              </div>
            </template>
          </px-table-column>
          <px-table-column label="操作" width="150" fixed="right" align="center">
            <template #default="scope">
              <px-tooltip content="详情" placement="top">
                <px-button link icon="Tickets" type="primary" @click="handleDetail(scope.row)" />
              </px-tooltip>
              <px-tooltip content="处理" placement="top">
                <px-button link icon="ChevronRightCircle" type="primary" @click="handleResolve(scope.row)" />
              </px-tooltip>
              <px-tooltip content="删除" placement="top">
                <px-button link icon="Delete" type="danger" @click="handleDelete(scope.row)" />
              </px-tooltip>
            </template>
          </px-table-column>
        </px-table>
        <pagination
          v-show="total > 0"
          v-model:page="pageNum"
          v-model:limit="pageSize"
          class="table-pagination"
          :total="total"
          @pagination="handleQuery"
        />
      </div>
    </template>
    <div v-if="resolveVisible">
      <Resolve v-model:visible="resolveVisible" :handleType="handleType" :rowData="rowData" type="1" @refresh="refresh" />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted, onActivated } from "vue";
import CustomTabs from "@/components/Tabs/index.vue";
import { queryDictData } from "@/api/common";
import { getListAPI, deleteListDataAPI } from "@/api/energy/monitor";
import { PxMessage, PxMessageBox } from "px-ui";
import Resolve from "@/views/common/energy/monitor/common/component/resolve.vue";
import { formatPeriod, formatAlarm, formatEventType, eventTypeStyle } from "@/views/common/energy/monitor/common/utils";

import { useRouter } from "vue-router";

defineOptions({
  name: "ALL_ENERGY_MONITOR_ENERGYMONITOR"
});

const router = useRouter();

const formRef = ref();

const state = reactive({
  monitorType: "consume",
  queryParams: {
    cycle: "",
    energy: "",
    date: ""
  },
  cycleList: [
    {
      value: "D",
      name: "每日"
    },
    {
      value: "M",
      name: "每月"
    }
  ],
  energyList: [],
  tableLoading: false,
  tableData: [],
  rowData: {},
  total: 10,
  pageNum: 1,
  pageSize: 20,
  resolveVisible: false,
  handleType: "Resolve"
});
const { queryParams, cycleList, tableLoading, tableData, rowData, total, pageNum, pageSize, resolveVisible, handleType } = toRefs(state);

const tabList = ref([
  { name: "", label: "全部" },
  { name: "N", label: "待处理" },
  { name: "H", label: "处理中" },
  { name: "C", label: "已完成" }
]);
const activeName = ref("");

// 切换tab
const handelTabSelected = val => {
  activeName.value = val;
  handleQuery();
};

onMounted(() => {
  // 双碳页面跳转带id过来
  if (router.currentRoute.value.query.id) {
    state.handleType = "Detail";
    state.resolveVisible = true;
  }
  getEnergySelect();
  handleQuery();
});

onActivated(() => {
  // 双碳页面跳转带id过来
  if (router.currentRoute.value.query.id) {
    state.handleType = "Detail";
    state.resolveVisible = true;
  }
  getEnergySelect();
  handleQuery();
});

// 获取能源下拉框数据
const getEnergySelect = async () => {
  const energyList = await queryDictData({ typeCode: "ENERGY" });
  state.energyList = [...energyList];
};

// 查询
const handleQuery = async () => {
  try {
    state.tableLoading = true;
    const { cycle, energy, date } = state.queryParams;
    const params = {
      pageNum: state.pageNum,
      pageSize: state.pageSize,
      alarmLevel: "",
      kind: activeName.value === "" ? null : activeName.value,
      period: cycle === "" ? null : cycle,
      alarmTimeStart: date === null || date === "" ? "" : date?.[0] + " 00:00:00",
      alarmTimeEnd: date === null || date === "" ? "" : date?.[1] + " 23:59:59",
      energyType: energy === "" ? null : energy,
      monitorType: state.monitorType
    };
    const res = await getListAPI(params);
    if (res?.data?.length) {
      let data = res?.data ?? [];
      data?.forEach(i => {
        i.supplyMaxText = (i?.supplyMaxValue ?? "-") + (i?.supplyUnit ?? "");
        i.spcThresholdText = (i?.spcThreshold ?? "-") + (i.unit ?? "");
        i.hseThresholdText = (i?.hseThreshold ?? "-") + (i.unit ?? "");
      });
      state.total = res.total;
      state.tableData = data;
    } else {
      state.total = 0;
      state.tableData = [];
    }
  } catch (err) {
    console.log(err);
  } finally {
    state.tableLoading = false;
  }
};

// 重置
const resetQuery = () => {
  formRef.value.resetFields();
  handleQuery();
};

// 详情
const handleDetail = row => {
  state.handleType = "Detail";
  state.rowData = row;
  state.resolveVisible = true;
};

// 处理
const handleResolve = row => {
  state.handleType = "Resolve";
  state.rowData = row;
  state.resolveVisible = true;
};

// 删除
const handleDelete = row => {
  const params = {
    id: row.id
  };
  sureDelete(params);
};

const sureDelete = async params => {
  PxMessageBox.confirm("是否确认删除？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      const res = await deleteListDataAPI(params);
      if (res.length > 0) {
        PxMessage.error(res);
      } else {
        PxMessage.success("删除成功");
        handleQuery();
      }
    })
    .catch(() => {});
};

const refresh = () => {
  state.resolveVisible = false;
  handleQuery();
};
</script>

<style lang="scss" scoped>
@import url("@/views/common/energy/monitor/common/scss/common.scss");
</style>
